package vn.demand.dragon.view
{
	import com.adobe.utils.StringUtil;
	
	import flash.events.Event;
	
	import flexed.widgets.alerts.alert;
	
	import mx.controls.Alert;
	import mx.events.CloseEvent;
	import mx.formatters.DateFormatter;
	
	import org.puremvc.as3.interfaces.IMediator;
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;
	
	import vn.demand.dragon.CommonCommand;
	import vn.demand.dragon.FFIAApplicationFacade;
	import vn.demand.dragon.model.MasterdataProxy;
	import vn.demand.dragon.model.ReferenceProxy;
	import vn.demand.dragon.view.components.ProjectForm;
	
	public class ProjectNewFormMediator extends Mediator implements IMediator
	{
		 // Cannonical name of the Mediator
        public static const NAME:String = "ProjectNewFormMediator";

        private var projectVO:Object;
        
        private var masterdataProxy:MasterdataProxy = null;
        
        private var projectProxy:ReferenceProxy = null;
        
        private var errorString:String;
        
        public static function makeId(projectVO:Object):String {
        	return NAME + "::" + projectVO.project_iso_code;
        }

		/**
         * Constructor. 
         */
        public function ProjectNewFormMediator(projectVO:Object, mediatorId:String, viewComponent:Object ) 
        {
            // pass the viewComponent to the superclass where 
            // it will be stored in the inherited viewComponent property
            super( mediatorId, viewComponent );
			
			projectForm.addEventListener(ProjectForm.PROJECT_FORM_UI_CREATED, prepareData);
			projectForm.addEventListener(ProjectForm.SAVE_PROJECT, onSave);
			projectForm.addEventListener(ProjectForm.CLOSE_PROJECT_FORM, onCloseForm);
			projectForm.addEventListener(ProjectForm.ADD_COMPANY, onAddCompany);
			projectForm.addEventListener(ProjectForm.ADD_SUPPLIER, onAddSupplier);
			
			this.projectVO = projectVO;
			
			projectForm.label = "" + projectVO.project_iso_code;
			
			masterdataProxy = facade.retrieveProxy(MasterdataProxy.NAME) as MasterdataProxy;
			projectProxy = facade.retrieveProxy(ReferenceProxy.NAME) as ReferenceProxy;
        }
        
        private function prepareData(event:Event):void {
        	projectForm.canEdit = true;
        	projectForm.canSave = true;
        	
        	projectForm.project_currency.dataProvider = masterdataProxy.currenciesDP;
        	projectForm.project_customer.dataProvider = masterdataProxy.customersDP;
        	projectForm.project_shipping_type.dataProvider = masterdataProxy.shippingTypesDP;
        	projectForm.project_status.dataProvider = masterdataProxy.projectStatusDP;
//        	projectForm.project_type.dataProvider = masterdataProxy.projectTypeDP;
        	projectForm.project_shipper.dataProvider = masterdataProxy.supplierDP;
        	
        	projectForm.project_currency.selectedIndex = 0;
        	projectForm.project_customer.selectedIndex = 0;
        	projectForm.project_shipping_type.selectedIndex = 0;
        	projectForm.project_status.selectedIndex = 2;
//        	projectForm.project_type.selectedIndex = 0;
        	projectForm.project_shipper.selectedIndex = 0;
        	
        	projectForm.project_date.selectedDate = new Date();
        	
        	projectForm.project_status.enabled = false;
        }
        
        private function onCloseForm(event:Event):void {
        	sendNotification(FFIAApplicationFacade.CLOSE_NEW_PROJECT_PANEL, projectForm);
        }
        
        private function onSave(event:Event):void {
        	doSave();
        }
        
        public function onAddCompany(event:Event):void {
//			var quickCompanyMediator:QuickCompanyMediator = facade.retrieveMediator(QuickCompanyMediator.NAME) as QuickCompanyMediator;
//			quickCompanyMediator.show();
		}
        
        public function onAddSupplier(event:Event):void {
//			var quickSupplierMediator:QuickSupplierMediator = facade.retrieveMediator(QuickSupplierMediator.NAME) as QuickSupplierMediator;
//			quickSupplierMediator.show();
			sendNotification(CommonCommand.ADD_SUPPLIER);
		}
        
        private function doSave():Boolean {
        	if (doValidate() == false) {
        		alert.error(errorString);
        		return false;
        	}
        	
        	
        	projectVO.project_name = projectForm.project_name.text;
        	projectVO.project_company = projectForm.project_customer.selectedData;
        	projectVO.project_currency = projectForm.project_currency.selectedData;
//        	projectVO.project_rtype = projectForm.project_type.selectedData;
        	projectVO.project_shipper = projectForm.project_shipper.selectedData;
        	projectVO.project_shipping_type = projectForm.project_shipping_type.selectedData;
        	
        	var df:DateFormatter = new DateFormatter();
        	df.formatString = 'YYYY-MM-DD';
        	projectVO.project_start_date = df.format(projectForm.project_start_date.selectedDate);
        	
        	projectVO.project_date =   df.format(projectForm.project_date.selectedDate);
        	
        	projectVO.project_description = projectForm.project_remarks.text;
        	
        	projectProxy.save(projectVO);
        	return true;
        }
        
        private function doValidate():Boolean {
        	errorString = "";
        	if (StringUtil.trim(projectForm.project_name.text) == '') {
        		errorString += "Please input [Reference Name]\n";
        	}
        	if (!(Number(projectForm.project_customer.selectedData) > 0)) {
        		errorString += "Please select [Customer]\n";
        	}
        	if (projectForm.project_date.selectedDate == null) {
        		errorString += "Please select [Reference Date]\n";
        	}
        	if (!(Number(projectForm.project_shipping_type.selectedData) > 0)) {
        		errorString += "Please select [Shipping Type]\n";
        	}
        	if (!(Number(projectForm.project_shipper.selectedData) > 0)) {
        		errorString += "Please select [Shipper]\n";
        	}
        	if (!(Number(projectForm.project_currency.selectedData) > 0)) {
        		errorString += "Please select [Currency]\n";
        	}
        	return !(errorString.length > 0);
        }
        
        public function get projectForm():ProjectForm
		{
            return viewComponent as ProjectForm;
        }
        
        override public function listNotificationInterests():Array 
        {
            return [ 
            	FFIAApplicationFacade.PROJECT_UPDATED,
            	FFIAApplicationFacade.PROJECT_UPDATE_FAILED,
            	FFIAApplicationFacade.CLOSE_NEW_PROJECT_PANEL,
            	CommonCommand.CLOSE_TAB,
            	
					 ];
        }
        
        override public function handleNotification( note:INotification ):void 
        {
            switch ( note.getName() ) 
			{
				case FFIAApplicationFacade.PROJECT_UPDATED:
					if (note.getType() != projectVO.project_iso_code) {
		        		return;
		        	}
					var o:Object = note.getBody();
					projectVO.project_id = o.id;
					sendNotification(FFIAApplicationFacade.CLOSE_FINISH_NEW_PROJECT_PANEL, projectVO, o.iso_code);
					break;
				case FFIAApplicationFacade.PROJECT_UPDATE_FAILED:
					if (note.getType() != projectVO.project_iso_code) {
		        		return;
		        	}
					alert.error(note.getBody() as String);
					break;
				case FFIAApplicationFacade.CLOSE_NEW_PROJECT_PANEL:
				case CommonCommand.CLOSE_TAB:
					var form = note.getBody() as ProjectForm;
					if (form != projectForm) {
						return;
					}
					if (projectForm.canSave) {
						alert.confirm("Do you want to save?", handleConfirmSave, Alert.CANCEL);
					}
					break;
                default:
                	break;
            }
        }
        
        private function handleConfirmSave(event:CloseEvent) {
        	if (event.detail == Alert.CANCEL) {
        		return;
        	}
        	if (event.detail == Alert.NO) {
        		sendNotification(FFIAApplicationFacade.CLOSE_FINISH_NEW_PROJECT_PANEL, projectVO);
        		return;
        	}
        	var canClose:Boolean = true;
        	canClose = doSave();
        	if (canClose) {
        		sendNotification(FFIAApplicationFacade.CLOSE_FINISH_NEW_PROJECT_PANEL, projectVO);        		
        	}
        } 
	}
}